package com.xzy.service.impl;

import com.xzy.dao.IBookDao;
import com.xzy.dao.IOrderDao;
import com.xzy.dao.IOrderItemDao;
import com.xzy.dao.impl.BookDaoImpl;
import com.xzy.dao.impl.OrderDaoImpl;
import com.xzy.dao.impl.OrderItemDaoImpl;
import com.xzy.domain.*;
import com.xzy.service.IOrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements IOrderService {
    IOrderDao dao = new OrderDaoImpl();
    IOrderItemDao ItemDao = new OrderItemDaoImpl();
   IBookDao bookDao = new BookDaoImpl();
    @Override
    public String settlement(Cart<BookCartItem> cart, Integer userid) {
        String orderid = System.currentTimeMillis()+""+userid;
        Order order = new Order(orderid, new Date(),
                cart.getTotalPrice(), 0, userid);
        dao.addOrder(order);

        Map<Integer, BookCartItem> items = cart.getItems();
        for (BookCartItem book : items.values()) {
            ItemDao.addOrderItem(new OrderItem(null,book.getName(),book.getCount(),book.getPrice(), book.getTotalPrice(),orderid));

            Book book1 = bookDao.quaryByid(book.getId());
            book1.setSales(book1.getSales()+book.getCount());
            book1.setStock(book1.getStock()-book.getCount());

            bookDao.updataBook(book1);

        }

            return order.getOrder_id();
    }


    @Override
    public List<Order> queryById(int userid) {
        List<Order> orders = dao.queryByUserid(userid);
        return orders;
    }

    @Override
    public List<Order> query() {

        List<Order> orders = dao.queryAll();
        return orders;
    }

    @Override
    public void updataStatus(String orderid, Integer status) {
        dao.updataStatus(orderid,status);
    }
}
